<?php

declare(strict_types=1);

namespace app\home\controller;

use app\BaseController;
use app\common\model\Collect;
use app\common\model\Config as ConfigModel;
use app\common\model\Region;
use think\facade\Db;
use app\common\model\User\User as UserModel;
use app\common\model\Post\Post as PostModel;
use app\common\model\Post\Comment as CommentModel;
use app\common\validate\User\User as UserValiDate;
use think\exception\ValidateException;

class User extends BaseController
{
    // 设置控制器中间件
    protected $middleware = [
        \app\home\middleware\LoginAuth::class
    ];
    protected function initialize()
    {
        parent::initialize();
        $this->UserModel = new UserModel();
        $this->Collect = new Collect();
    }
    public function index()
    {
        // 接收地址栏里的userid
        $userid = $this->request->param('userid');
        if ($userid) {
            // 查询该用户的数据
            $User = $this->UserModel->find($userid);
            if (!$User) {
                $this->error('用户不存在，请重新选择');
            }
        }
        // 如果有接收用户id拿查询的数据给视图，否则把登录的数据给视图
        $User = $userid ? $User : $this->request->LoginUser;
        // 查询该用户的帖子
        $PostList = PostModel::order('createtime', 'desc')->where(['userid' => $User['id']])->paginate(['list_rows' => 10, 'query' => $this->request->param()]);

        $CommentList=CommentModel::with(['post'])->order('createtime', 'desc')->where(['userid'=>$User['id']])->paginate(['list_rows' => 3, 'query' => $this->request->param()]);
        return view(
            '',
            [
                'User' => $User,
                'PostList' => $PostList,
                'CommentList'=>$CommentList,
                
            ]
        );
    }
    // 基本资料
    public function profile()
    {
        $title = '基本设置';
        $LoginUser = $this->request->LoginUser;

        if ($this->request->isPost()) {
            $action = $this->request->param('action');
            $user = $this->UserModel->find($LoginUser['id']);
            if (!$user) {
                cookie('LoginUser', null);
                $this->error('非法登录', (string)url('/home/index/login'));
            }
            if ($action == 'profile') {
                $param = $this->request->param();
                $data = [
                    'nickname' => $param['nickname'],
                    'sex' => $param['sex'],
                    'content' => $param['content']
                ];

                if (!empty($param['district'])) {
                    $parentpath = Region::where('code', $param['district'])->value('parentpath');

                    if (!$parentpath) {
                        $this->error('所选地区不存在，请重新选择');
                    }

                    [$province, $city, $district] = explode(',', $parentpath);

                    if ($province) {
                        $data['province'] = $province;
                    }

                    if ($province) {
                        $data['city'] = $city;
                    }

                    if ($province) {
                        $data['district'] = $district;
                    }
                }

                try {
                    validate(UserValiDate::class)->scene('profile')->check($data);
                } catch (ValidateException $e) {
                    $this->error($e->getError());
                }

                $result = $user->save($data);

                if ($result === FALSE) {
                    $this->error('更新资料失败');
                } else {

                    $User = $this->UserModel->find($LoginUser['id']);

                    // 封装cookie数组
                    $data = [
                        'id' => $User['id'],
                        'email' => $User['email'],
                        'nickname' => $User['nickname'],
                        'avatar' => $User['avatar'],
                        'sex' => $User['sex'],
                        'province' => $User['province'],
                        'city' => $User['city'],
                        'district' => $User['district'],
                        'content' => $User['content'],
                        'point' => $User['point'],
                        'vip' => $User['vip'],
                        'auth' => $User['auth'],
                        'cover' => $User['cover'],
                        'createtime' => $User['createtime'],
                    ];

                    // 转成json字符串
                    $json = json_encode($data);
                    // cookie 助手函数
                    cookie('LoginUser', $json);
                    $this->success('更新资料成功', (string)url('/home/user/index'));
                }
            }
            if ($action == 'avatar') {
                // 更新头像
                $avatar = upload('avatar');
                if ($avatar['code'] === 0) {
                    $this->error($avatar['msg']);
                }
                $data = [
                    'avatar' => $avatar['data']
                ];
                $avatardata = $avatar['data'] ? $avatar['data'] : '';
                $avatardata = ltrim($avatardata, '/');
                // 新注册的账号cookie头像为空，会报错
                $useravatar = $user['avatar'] ? $user['avatar'] : '';
                $useravatar = ltrim($useravatar, '/');
                $result = $user->save($data);
                if ($result === false) {
                    if ($_FILES['avatar']['size'] > 0 && isset($avatar['data'])) {
                        @is_file($avatardata) && @unlink($avatardata);
                    }
                    $this->error('上传失败');
                } else {
                    if ($_FILES['avatar']['size'] > 0 && isset($avatar['data'])) {
                        @is_file($useravatar) && @unlink($useravatar);
                    }
                    $User = $this->UserModel->find($LoginUser['id']);
                    // 封装cookie数组
                    $data = [
                        'id' => $User['id'],
                        'email' => $User['email'],
                        'nickname' => $User['nickname'],
                        'avatar' => $User['avatar'],
                        'sex' => $User['sex'],
                        'province' => $User['province'],
                        'city' => $User['city'],
                        'district' => $User['district'],
                        'content' => $User['content'],
                        'point' => $User['point'],
                        'vip' => $User['vip'],
                        'auth' => $User['auth'],
                        'cover' => $User['cover'],
                        'createtime' => $User['createtime'],
                    ];

                    // 转成json字符串
                    $json = json_encode($data);
                    // cookie 助手函数
                    cookie('LoginUser', $json);
                    $this->success('上传成功', (string)url('/home/user/profile'));
                }
            }
            if ($action == 'password') {
                $param = $this->request->param();
                if ($user['password'] != md5($param['nowpass'] . $user['salt'])) {
                    $this->error('原密码错误，请重新输入');
                }
                if ($param['pass'] != $param['repass']) {
                    $this->error('新密码前后输入不一致，请重新输入');
                }
                $pass = md5($param['pass'] . $user['salt']);
                if ($pass == $user['password']) {
                    $this->error('新密码不能与原密码一致，请重新输入');
                }
                $salt = build_ranstr();
                $password = md5($param['pass'] . $salt);
                $data = [
                    'salt' => $salt,
                    'password' => $password,
                ];
                $result = $user->save($data);
                if ($result === FALSE) {
                    $this->error('修改密码失败');
                } else {
                    cookie('LoginUser', null);
                    $this->success('修改成功，请重新登录', (string)url('/home/index/login'));
                }
            }
            if ($action == 'cover') {
                $cover = upload('cover');
                if ($cover['code'] === 0) {
                    $this->error($cover['msg']);
                }
                $data = [
                    'cover' => $cover['data']
                ];
                $coverdata = $cover['data'] ? $cover['data'] : '';
                $coverdata = ltrim($coverdata, '/');
                $usercover = $user['cover'] ? $user['cover'] : '';
                $usercover = ltrim($usercover, '/');
                $result = $user->save($data);
                if ($result === false) {
                    if ($_FILES['cover']['size'] > 0 && isset($cover['data'])) {
                        @is_file($coverdata) && @unlink($coverdata);
                    }
                    $this->error('上传失败');
                } else {
                    if ($_FILES['cover']['size'] > 0 && isset($cover['data'])) {
                        @is_file($usercover) && @unlink($usercover);
                    }
                    $User = $this->UserModel->find($LoginUser['id']);
                    // 封装cookie数组
                    $data = [
                        'id' => $User['id'],
                        'email' => $User['email'],
                        'nickname' => $User['nickname'],
                        'avatar' => $User['avatar'],
                        'sex' => $User['sex'],
                        'province' => $User['province'],
                        'city' => $User['city'],
                        'district' => $User['district'],
                        'content' => $User['content'],
                        'point' => $User['point'],
                        'vip' => $User['vip'],
                        'auth' => $User['auth'],
                        'cover' => $User['cover'],
                        'createtime' => $User['createtime'],
                    ];

                    // 转成json字符串
                    $json = json_encode($data);
                    // cookie 助手函数
                    cookie('LoginUser', $json);
                    $this->success('上传成功', (string)url('/home/user/profile'));
                }
            }
        }

        // 查询所有的数据
        $province = Region::where(['grade' => 1])->select();
        if ($LoginUser['province']) {
            $city = Region::where('parentid', $LoginUser['province'])->select();
        } else {
            $city = [];
        }
        if ($LoginUser['city']) {
            $district = Region::where('parentid', $LoginUser['city'])->select();
        } else {
            $district = [];
        }
        return view('', [
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'title' => $title
        ]);
    }
    // 我的发帖/收藏
    public function mypost()
    {
        $title = '我的发帖';
        $LoginUser = $this->request->LoginUser;
        // 发帖
        $PostList = PostModel::order('createtime', 'desc')->where(['userid' => $LoginUser['id']])->paginate(['list_rows' => 10, 'query' => $this->request->param()]);
        // halt($PostList);
        $postcount = count($PostList);
        // 收藏
        $CollectList = Collect::withJoin(['post'])->where('deletetime', 'exp', Db::raw('IS NULL'))->order('createtime', 'desc')->where(['collect.userid' => $LoginUser['id']])->paginate(['list_rows' => 10, 'query' => $this->request->param()]);
        // halt($CollectList);
        $collectcount = count($CollectList);
        if ($this->request->isAjax()) {
            $collectid = $this->request->param('collectid');
            $collect = Collect::find(['id' => $collectid]);
            if (!$collect) {
                $this->error('该收藏不存在');
            }
            $result = $this->Collect->where(['id' => $collectid])->delete();
            if ($result !== FALSE) {
                $this->success('取消收藏成功', (string)url('/home/user/mypost'));
            } else {
                $this->error('取消收藏失败');
            }
        }
        return view('', [
            'title' => $title,
            'PostList' => $PostList,
            'postcount' => $postcount,
            'CollectList' => $CollectList,
            'collectcount' => $collectcount
        ]);
    }
    // 地址选择
    public function area()
    {
        $code = $this->request->param('code');

        $list = Region::where(['parentid' => $code])->select();

        if (!$list) {
            $this->error('所选地区不存在，请重新选择');
        }

        $this->success('查询成功', null, $list);
    }
    // 邮箱认证
    public function email()
    {
        // 通过中间件赋值给所有控制器
        $LoginUser = $this->request->LoginUser;
        $salt = $this->UserModel->where(['id' => $LoginUser['id']])->value('salt');;
        $email = $this->request->param('email');
        $nickname = $this->request->param('nickname');
        $Email = md5($email . $salt);
        $cdn = ConfigModel::where(['key' => 'cdn'])->value('value');

        $content = "<a href='$cdn/home/index/email?email=$Email'>点击认证</a>";

        $result = EmailSend($nickname, $email,  $content);
        if ($result === FALSE) {
            $this->error('发送邮件失败');
        } else {
            $this->success('发送邮件成功');
        }
    }
    // 修改密码
    public function password()
    {
        return view();
    }
}
